<template>
  <md-nav-bar title="" />
  <view class="container">
    <view class="top_desc">
      <view class="title ellipsis-2">{{ data.info?.title }}</view>
      <view class="date m-top-26">
        <view class="flex-b">
          <view class="flex-l">
            <md-icon name="clock" width="30" height="30" />
            {{ data.info?.createtime }}
          </view>
          <button class="m-all-0 p-all-0 raidus-lg" open-type="share">
            <md-icon :url="data.configInfo?.share_icon" width="140" height="64" />
          </button>
        </view>
      </view>
      <!-- 富文本 -->
      <view class="content">
        <swiper
          circular
          class="swiper-box"
          layout-type="transformer"
          transformer-type="scaleAndFade"
          :current="data.current">
          <swiper-item v-for="(item, index) in data.info?.img_arr" :key="index">
            <view class="img_arr" :style="{ background: `url(${item}) center center / contain no-repeat` }"></view>
            
            <!-- <image :src="item" mode="aspectFill" class="img_arr"></image> -->
          </swiper-item>
        </swiper>
        <view class="m-top-38">{{ data.info?.content }}</view>
      </view>
    </view>
    <view class="comment-list m-top-20">
      <mescroll-body @init="mescrollInit" @down="downCallback" @up="upCallback" :safearea="true" bottom="80px">
        <CommentList
          :list="data.list"
          :color="data.configInfo.select_color_text"
          @reply="handleReply"
          @del="handleDel"></CommentList>
      </mescroll-body>
    </view>
    <!-- 底部按钮 -->
    <view class="btn">
      <view class="input" @click="() => (data.review_id = null)">
        <input
          v-model="data.content"
          style="width: 100%; height: 100%"
          :placeholder="data.placeholder"
          confirm-type="send"
          :focus="data.focus"
          @blur="onBlur"
          @confirm="handleSend" />
      </view>
      <!-- 点赞 -->
      <view v-if="data.info" class="m-left-12" @click.stop="() => handleCollect(data.info, 2)">
        <md-dianzan :text="data.info.agree_num" collectKey="is_agree" :item="data.info" />
      </view>
      <!-- 收藏 -->
      <view v-if="data.info" class="m-left-12" @click.stop="() => handleCollect(data.info, 1)">
        <md-dianzan type="collect" :text="data.info.collect_num" :item="data.info" />
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { reactive } from 'vue';
import { onLoad, onShareAppMessage, onPageScroll, onReachBottom } from '@dcloudio/uni-app';
// 组件
import CommentList from '@/components/comment-list/index.vue';
import useMescroll from '@/uni_modules/mescroll-uni/hooks/useMescroll.js';
// 接口
import {
  interactionCollect,
  interactionDelReview,
  interactionDetail,
  interactionReview,
  interactionReviewList,
} from '@/api';
import type { Interaction } from '@/api/data';
// 工具
import { Toast } from '@/utils/util';
const { mescrollInit, downCallback, getMescroll } = useMescroll(onPageScroll, onReachBottom);

const data = reactive<any>({
  id: -1,
  info: {},
  status: false,
  collectStauts: false,
  // 回复评论相关
  list: [],
  total: 0,
  review_id: null,
  content: '',
  focus: false,
  placeholder: '我有话要说...',
  configInfo: {},
});

// 分享钩子
onShareAppMessage(res => {
  return {
    title: '互动详情',
    imageUrl: data.configInfo?.share_poster,
    path: '/pages/interact/i-detail?id=' + data.id,
  };
});

// 收藏 | 点赞回调
const handleCollect = async (item: Interaction.Index.Data, type: number) => {
  // 1收藏 2点赞
  const typeCode = type === 1 ? 'collect' : 'agree';
  item[`is_${typeCode}`] = !item[`is_${typeCode}`];
  if (!!item[`is_${typeCode}`]) {
    item[`${typeCode}_num`] += 1;
  } else {
    item[`${typeCode}_num`] -= 1;
  }
  const res = await interactionCollect({ id: item.id, collect_type: type });
  Toast(res.msg);
};

// 发送回复信息
const handleSend = async () => {
  await fetchInteractionReviewList({ review_id: data.review_id, content: data.content });
};

// 点击回复回调，获取评论id
const handleReply = (item: Interaction.Review.List.Data) => {
  data.review_id = item.id;
  data.placeholder = `回复评论：${item.content}`;
  data.focus = true;
};

// 删除评论
const handleDel = (id: number) => {
  uni.showModal({
    title: '提示',
    content: '是否删除该条记录？',
    success: res => {
      if (res.confirm) {
        fetchInteractionDelReview(id);
      }
    },
  });
};

// 失焦事件
const onBlur = () => {
  data.placeholder = '我有话要说...';
  data.focus = false;
};

/**
 * 接口相关
 */
// 互动详情
const fetchInteractionDetail = async (id: number) => {
  try {
    const res = await interactionDetail({ id });
    data.info = res.data;
  } catch (e) {
    //TODO handle the exception
  }
};

// 互动评论列表
const upCallback = async (mescroll: any) => {
  try {
    let res = await interactionReviewList({
      page: mescroll.num,
      limit: mescroll.size,
      interaction_id: data.id,
    });
    const curPageData = res?.data?.data || []; // 当前页数据
    if (mescroll.num == 1) data.list = []; // 第一页需手动制空列表
    data.list = data.list.concat(curPageData); //追加新数据
    mescroll.endByPage(curPageData.length, res?.data?.total);
  } catch (e) {
    //TODO handle the exception
    mescroll.endErr(); // 请求失败, 结束加载
  }
};

// 发布评论
const fetchInteractionReviewList = async (params: { review_id: string; content: string }) => {
  try {
    await interactionReview({
      id: data.id, // 帖子id
      ...params,
    });
    data.focus = false;
    data.reply_id = null;
    data.content = '';
    getMescroll()?.resetUpScroll();
  } catch (error) {}
};

// 删除评论
const fetchInteractionDelReview = async (id: number) => {
  try {
    await interactionDelReview({
      review_id: id + '',
    });
    getMescroll()?.resetUpScroll();
  } catch (error) {}
};

onLoad(option => {
  // 获取全局配置
  const configInfo = uni.getStorageSync('configInfo');
  if (Object.keys(configInfo || {})?.length > 0) {
    const parseInfo = JSON.parse(configInfo);
    data.configInfo = parseInfo;
  }
  // console.log(option);
  data.id = option?.id;
  fetchInteractionDetail(option?.id);

  uni.showShareMenu({
    withShareTicket: true,
    menus: ['shareAppMessage', 'shareTimeline'],
  });
});
</script>

<style lang="scss" scoped>
.container {
  .top_desc {
    padding: 40rpx 30rpx;
    background: white;
    .title {
      font-size: $fs-40;
    }
    .date {
      color: $sub;
    }
    .content {
      margin-top: 42rpx;
      font-size: 28rpx;
      color: $title;
      .swiper-box {
        height: 740rpx;
        swiper-item {
          text-align: center;
          image {
            // width: inherit;
            max-height: 100%;
            max-width: 100%;
          }
        }
      }
    }
  }
  .raidus-lg {
    &::after{
      border: none;
    }
  }
  .img_arr {
    // height: 460rpx;
    // height: 100%;
    width: 100%;
    flex-shrink: 0;
    height: 100%;
    object-fit: contain;
    align-items: center;
    display: flex;
    justify-content: center;
    position: relative;
  }
}

.comment-list {
  background: white;
}

// 底部按钮
.btn {
  width: 100%;
  background: white;
  position: fixed;
  left: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  padding: 30rpx 30rpx $safe-bottom;
  box-sizing: border-box;
  border-top: 1rpx solid #e6e6e6;
  .input {
    flex: 1;
    height: 60rpx;
    line-height: 60rpx;
    border-radius: 30rpx;
    padding: 0 27rpx;
    color: #a5a5a5;
    font-size: $fs-28;
    background: #f2f2f2;
  }
  .dianzan,
  .collect {
    margin-left: 12rpx;
  }
}
</style>
